package com.uzai.console.service.user.impl;

import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.IdentityEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.dto.user.usertype.UserTypeQuery;
import com.uzai.console.dto.user.wechatuser.BatchUpdateDefaultClientDto;
import com.uzai.console.dto.user.wechatuser.UpdateDefaultClientPersonal;
import com.uzai.console.dto.user.wechatuser.UpdateDefaultClientPersonalDto;
import com.uzai.console.dto.user.wxworkuser.WxworkBatchUpdateDefaultClientDto;
import com.uzai.console.dto.user.wxworkuser.WxworkUpdateDefaultClientPersonal;
import com.uzai.console.dto.user.wxworkuser.WxworkUpdateDefaultClientPersonalDto;
import com.uzai.console.dto.user.wxworkuser.WxworkUserDeviceUniqueIdDto;
import com.uzai.console.entity.ConfigPlan;
import com.uzai.console.entity.DeviceWxworkInfo;
import com.uzai.console.entity.UserType;
import com.uzai.console.entity.UserTypeGroup;
import com.uzai.console.mapper.*;
import com.uzai.console.service.user.WxworkUserBatchService;
import com.uzai.console.service.user.WxworkUserSyncService;
import com.uzai.console.vo.user.usertype.UserTypeInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class WxworkUserBatchServiceImpl implements WxworkUserBatchService {

    private Logger logger = LoggerFactory.getLogger(WxworkUserBatchServiceImpl.class);

    @Autowired
    private WxworkUserSyncService wxworkUserSyncService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;

    /**
     * 查询会员类型列表根据机器人id
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUserDeviceUniqueIdDto
     * @return null
     */
    public List<UserTypeInfoVo> findUserTypeListByDeviceUniqueId(WxworkUserDeviceUniqueIdDto wxworkUserDeviceUniqueIdDto){
        //返回的会员类型对象
        List<UserTypeInfoVo> userTypeInfoVoList = new ArrayList<>();
        Long merId = wxworkUserDeviceUniqueIdDto.getMerId();//运营商id
        Long deviceUniqueId = wxworkUserDeviceUniqueIdDto.getDeviceUniqueId(); //机器人唯一id
        if(merId != null && deviceUniqueId != null){
            //查询机器人信息
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceUniqueId, merId);
            if(deviceWxworkInfo != null){
                if(deviceWxworkInfo.getConfigId() != null){
                    //查询机器人的配置方案
                    ConfigPlan configPlan = configPlanMapper.selectById(deviceWxworkInfo.getConfigId(), merId);
                    if(configPlan != null){
                        //查询该配置方案的会员类型组id
                        Long userTypeGroupId = configPlan.getUserTypeGroupId();
                        if(userTypeGroupId != null){
                            UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, merId);
                            if(userTypeGroup != null){
                                UserTypeQuery userTypeQuery = new UserTypeQuery();
                                userTypeQuery.setMerId(merId);
                                userTypeQuery.setGroupId(userTypeGroupId);
                                //查询该挥会员类型组包含的会员类型
                                List<UserType> userTypeList = userTypeMapper.findByList(userTypeQuery);
                                if(userTypeList != null && userTypeList.size() > 0){
                                    for (UserType userType : userTypeList){
                                        UserTypeInfoVo userTypeInfoVo = new UserTypeInfoVo();
                                        BeanUtils.copyProperties(userType, userTypeInfoVo);
                                        userTypeInfoVo.setGroupName(userTypeGroup.getName());
                                        if(userTypeInfoVo.getIdentity() != null){
                                            IdentityEnum identityEnum = IdentityEnum.getById(userTypeInfoVo.getIdentity());
                                            if(identityEnum != null){
                                                userTypeInfoVo.setIdentityName(identityEnum.getDesc());
                                            }
                                        }
                                        userTypeInfoVoList.add(userTypeInfoVo);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return userTypeInfoVoList;
    }


    /**
     * 修改个人微信默认客户端
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkBatchUpdateDefaultClientDto
     * @return null
     */
    public void updateDefaultClient(WxworkBatchUpdateDefaultClientDto wxworkBatchUpdateDefaultClientDto){

        Long merId = wxworkBatchUpdateDefaultClientDto.getMerId();
        if(merId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        Long deviceUniqueIdOld = wxworkBatchUpdateDefaultClientDto.getDeviceUniqueIdOld();
        if(deviceUniqueIdOld == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择旧机器人");
        }

        Long deviceUniqueIdNew = wxworkBatchUpdateDefaultClientDto.getDeviceUniqueIdNew();
        if(deviceUniqueIdNew == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择新机器人");
        }

        List<Long> userTypeIdOldList = wxworkBatchUpdateDefaultClientDto.getUserTypeIdOldList();

        if(userTypeIdOldList == null || userTypeIdOldList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入旧的会员类型id列表");
        }

        List<Long> userTypeIdNewList = wxworkBatchUpdateDefaultClientDto.getUserTypeIdNewList();
        if(userTypeIdNewList == null || userTypeIdNewList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入新的会员类型id列表");
        }

        //新的会员类型列表长度必须大于旧的会员类型列表长度
        if(userTypeIdNewList.size() < userTypeIdOldList.size()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新的会员类型列表长度必须大于旧的会员类型列表长度");
        }

        for(int i=0; i<userTypeIdOldList.size(); i++){
            Long userTypeIdOld = userTypeIdOldList.get(i);
            UserType userTypeOld = userTypeMapper.selectById(userTypeIdOld, merId);
            if(userTypeOld == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "旧会员类型不存在或者已经删除");
            }

            Long userTypeIdNew = userTypeIdNewList.get(i);
            UserType userTypeNew = userTypeMapper.selectById(userTypeIdNew, merId);
            if(userTypeNew == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新会员类型不存在或者已经删除");
            }

            if(Tools.getInteger(userTypeOld.getIdentity()).intValue() != Tools.getInteger(userTypeNew.getIdentity()).intValue()){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新会员类型身份与旧会员类型身份不一样");
            }
        }

        //从redis中获取上次更新的时间，判断12小时执行一次
        Object val = redisTemplate.opsForValue().get(String.format(CacheKey.WECHAT_USER_DEFAULT_CLIENT_OPE, merId));
        if (val != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "5分钟内只能更新一次");
        }

        //异步调用修改会员默认客户端
        wxworkUserSyncService.updateDefaultClientSync(wxworkBatchUpdateDefaultClientDto);

        //将本次更新操作记录到Redis当中，下次更新需要5分钟以后操作
        redisTemplate.opsForValue().set(String.format(CacheKey.WECHAT_USER_DEFAULT_CLIENT_OPE, merId), merId,5, TimeUnit.MINUTES);

    }

    /**
     * 修改个人微信单个会员默认客户端
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUpdateDefaultClientPersonalDto
     * @return null
     */
    public void updateDefaultClientPersonal(WxworkUpdateDefaultClientPersonalDto wxworkUpdateDefaultClientPersonalDto){

        Long merId = wxworkUpdateDefaultClientPersonalDto.getMerId();
        if(merId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //会员id
        Long id = wxworkUpdateDefaultClientPersonalDto.getId();
        if(id == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择会员id");
        }
        WxworkUser wxworkUser = wxworkUserMapper.selectById(id, merId);
        if(wxworkUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员不存在");
        }

        //新的机器人
        Long deviceUniqueIdNew = wxworkUpdateDefaultClientPersonalDto.getDeviceUniqueIdNew();
        if(deviceUniqueIdNew == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入新机器人id");
        }
        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceUniqueIdNew, merId);
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人不存在");
        }

        //新的会员类型
        Long userTypeIdNew = wxworkUpdateDefaultClientPersonalDto.getUserTypeIdNew();
        if(userTypeIdNew == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入新的会员类型");
        }
        UserType userTypeNew = userTypeMapper.selectById(userTypeIdNew, merId);
        if(userTypeNew == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新会员类型不存在或者已经删除");
        }

        if(Tools.getInteger(wxworkUser.getIdentity()).intValue() != Tools.getInteger(userTypeNew.getIdentity()).intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新会员类型身份与该会员身份不一样");
        }

        //修改会员默认客户端
        WxworkUpdateDefaultClientPersonal wxworkUpdateDefaultClientPersonal  = new WxworkUpdateDefaultClientPersonal();
        wxworkUpdateDefaultClientPersonal.setMerId(merId);
        wxworkUpdateDefaultClientPersonal.setId(id);
        wxworkUpdateDefaultClientPersonal.setDeviceUniqueIdNew(deviceUniqueIdNew);
        wxworkUpdateDefaultClientPersonal.setUserTypeIdNew(userTypeIdNew);
        wxworkUserMapper.updateDefaultClientPersonal(wxworkUpdateDefaultClientPersonal);

    }
}
